package com.gqz.aircraftwar.util

import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast

import com.gqz.aircraftwar.R


/**
 * Created by Administrator on 2017/8/31.
 */

object ToastUtils {

    private var oldMsg: String? = null
    private var toast: Toast? = null
    private var lastTime: Long = 0
    private var curTime: Long = 0

    //这种不会卡顿，但是频繁调用后有上限，要等待3s左右才能再次显示，正常情况很少有频繁调用的情况
    //    public static void showToast(Context context, String s) {
    //        if (toast == null) {
    //            toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
    //            toast.show();
    //            lastTime = System.currentTimeMillis();
    //        } else {
    //            curTime = System.currentTimeMillis();
    //            if (s.equals(oldMsg)) {
    //                if (curTime - lastTime > Toast.LENGTH_SHORT) {
    //                    toast.show();
    //                }
    //            } else {
    //                oldMsg = s;
    //                toast.setText(s);
    //                toast.show();
    //            }
    //        }
    //        lastTime = curTime;
    //    }

    //这种写法调用太频繁（4/s）会导致UI轻微卡顿
    fun showToast(context: Context, s: String) {
        //        if (toast != null) {
        //            toast.cancel();
        //        }
        //        toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
        //        toast.show();
        val v = LayoutInflater.from(context).inflate(R.layout.toast, null)
        showToast(context, s, v)
    }

    private fun showToast(context: Context, s: String, v: View) {
        toast?.cancel()
        toast = Toast(context)
        toast?.view = v
        toast?.duration = Toast.LENGTH_SHORT
        val tv = v.findViewById<TextView>(R.id.toast_tv)
        tv.text = s
        toast?.show()
    }


    fun showToast(context: Context, resId: Int) {
        showToast(context, context.getString(resId))
    }

}
